<template>
  <div class="customer-detail">
    <gl-breadcrumb class="mb15" text="客户管理,客户详情"></gl-breadcrumb>
    <div class="cus-detail bg p20">
      <div class="remark flex jcb">
        <div class="cus-name">
          <span class="name mr10">{{info.name}}</span>
          <span class="type">（{{info.customer_type}}）</span>
          <div class="company pl10">{{info.rate_name}}</div>
        </div>
        <el-button class="edit-cus el-icon-edit" plain type="primary" @click="showEdit = true"> 编辑</el-button>
      </div>
      <div class="info tac flex mt20">
        <div class="info-label flex-1"
             :class="label.prop"
             @click="infoCallback(label.prop)"
             v-for="(label, i) in infoLabel" :key="i">
          <div class="label">{{label.label}}</div>
          <div class="prop wsnw" :class="{'can-click': label.prop === 'userSum' || label.prop === 'contract_num'}">
            {{info[label.prop] || 0}}
          </div>
        </div>
      </div>
    </div>
    <div class="bg p20 mt20">
      <div class="def-title flex jcb">
        <div class="span">产品管理</div>
        <add-product-dialog :customer_id="$route.params.id * 1" @success="addProductSucc"></add-product-dialog>
      </div>
      <div class="product-list mb25 mt20">
        <gl-table v-loading="productLoading" :data="productList" :columns="productLabel" @button="btnCallback">
          <span @click="toAct(row)" class="csp act-count" slot="act"
                slot-scope="{row}">{{row.act_sum}}/{{row.sum}}</span>
        </gl-table>
        <gl-pagination :total="total" :curr="curr" :size="limits" @callback="currChange"></gl-pagination>
      </div>
      <div class="def-title flex jcb">
        <div class="span">终端设备</div>
        <el-button class="add el-icon-plus" plain type="primary" @click="showAddDevice = true">添加</el-button>
      </div>
      <div class="device-list flex jcb fww mt20 pl20 pr20">
        <div class="device-item flex jcb bsb mb20 p20" v-for="(device, i) in deviceList" :key="i">
          <img :src="device.model_icon" alt="" class="mr25 device-img">
          <div class="text flex-1">
            <div class="dev-name mb10">{{device.model_name}}</div>
            <div class="dev-other flex jcb" v-for="(label, k) in device.model_data_list" :key="k">
              <span class="wsnw">{{label.key_name}}</span>
              <span class="wsnw">{{label.value}}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <el-dialog title="编辑客户" :visible.sync="showEdit">
      <div class="df-title mb10">基本信息</div>
      <gl-form class=""
               ref="infoRef"
               must="name,rate_name,con_name,tel,bus_id"
               :form="cusInfo" :form-label="cusInfoLabel"></gl-form>
      <div class="df-title mb10">登录信息</div>
      <gl-form class=""
               ref="loginRef"
               :form="login" :form-label="loginLabel"></gl-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showEdit = false">取 消</el-button>
        <el-button type="primary" @click="edit">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="设备管理" :visible.sync="showAddDevice">
      <div class="device-dialog flex jcb fww">
        <div class="item por ovh mb10 bsb" v-for="(item, i) in deviceList" :key="i">
          <img :src="item.model_icon" alt="" class="img vam w100">
          <div class="poa btns r0 t0 transition zi1">
            <el-button type="text" class="el-icon-edit" @click="editDevice(item)"></el-button>
            <el-button type="text" class="el-icon-delete" @click="delDevice(item)"></el-button>
          </div>
          <div class="poa b0 l0 w100 title zi1 tac">{{item.model_name}}</div>
        </div>
        <div class="item por el-icon-plus add-item tac bsb csp fs24" @click="editDevice()"></div>
        <template v-if="(deviceList.length + 1) % 4">
          <div class="item bsb" v-for="e in 4 - (deviceList.length + 1) % 4"></div>
        </template>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAddDevice = false">取 消</el-button>
        <el-button type="primary" @click="showAddDevice = false">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog width="" :title="editDeviceForm.model_id ? '修改设备' : '新增设备'" :visible.sync="editDeviceInner">
      <gl-form class=""
               ref="deviForm"
               must="model_name"
               @upload="upload"
               :form="editDeviceForm" :form-label="editDeviceLabel">
        <div class="" slot="someProp">
          <div class="mb10" v-for="(device, d) in editDeviceForm.model_data_list" :key="i">
            <el-input class="w33" v-model="device.key_name"></el-input>
            :
            <el-input class="w33" v-model="device.value"></el-input>
            <el-button type="text" class="el-icon-close ml20"
                       @click="editDeviceForm.model_data_list.splice(d, 1)"></el-button>
          </div>
          <el-button type="primary" class="el-icon-plus" size="small" @click="editDeviceForm.model_data_list.push({})">
            添加设备参数项
          </el-button>
        </div>
      </gl-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDeviceInner = false">取 消</el-button>
        <el-button type="primary" @click="editDeviceSure">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import addProductDialog from './components/AddProductDialog';
  import {mapGetters} from 'vuex'

  export default {
    name: "CustomerDetails",
    components: {
      addProductDialog,
    },
    computed: {
      ...mapGetters(['userInfo'])
    },
    data() {
      return {
        productLoading: false,
        showEdit: false,
        cusInfo: {},
        cusInfoLabel: [
          {label: '客户简称:', prop: 'name'},
          {label: '公司名称:', prop: 'rate_name'},
          {label: '客户类型:', prop: 'type_id', options: [], labelKey: 'name', valueKey: 'id'},
          {label: '公司地址:', prop: 'address'},
          {label: '联系人:', prop: 'con_name'},
          {label: '联系方式:', prop: 'tel'},
          {label: '业务员:', prop: 'bus_id', options: [], labelKey: 'name', valueKey: 'id'},
          {label: '描述:', prop: 'remark', rows: 3, text: 'ueditor'},
        ],
        login: {},
        loginLabel: [
          {label: '登录账号:', prop: 'username', readonly: true},
          {label: '修改密码:', prop: 'password'},
          {label: '确认修改:', prop: 'repassword'},
        ],

        showAddDevice: false,
        addDevice: {},
        deviceLabel: [],


        infoLabel: [
          {label: '上线产品', prop: 'product_quantity'},
          {label: '关联用户', prop: 'userSum'},
          {label: '已激活设备', prop: 'deviceSum'},
          {label: '结款总额', prop: 'priceSum'},
          {label: '待激活总数', prop: 'waitSum'},
          {label: '订单总数', prop: 'orderSum'},
          {label: '合同', prop: 'contract_num'},
        ],
        info: {},

        productList: [],
        productLabel: [
          {label: '产品ID', prop: 'id', width: '100px'},
          {label: '产品名称', prop: 'name'},
          {label: '激活情况', prop: 'act', slot: 'act'},
          {label: '授权方式', prop: 'aw_name', width: '160px'},
          {label: '使用期限', prop: 'endtime', width: '100px', format: 's%天'},
          {label: '上线状态', prop: 'status', width: '80px'},
          {label: '操作', btns: ['产品详情', '订单详情'], width: '160px'},
        ],
        curr: 1,
        limits: 10,
        total: 0,

        deviceList: [],
        editDeviceInner: false,
        editDeviceLabel: [
          {label: '设备名称', prop: 'model_name'},
          {label: '图片', prop: 'model_icon', type: 'upload',limit:1},
          {label: '设置参数', slot: 'someProp', prop: 'model_data_list'},
          {label: '备注', prop: 'remark', rows: 3, text: 'ueditor'},
        ],
        editDeviceForm: {},
      }
    },
    watch: {
      showEdit(val) {
        if (val) {
          this.getSelects();
          this.cusInfo = {...this.info};
        } else {
          this.$refs.infoRef.resetFields();
          this.$refs.loginRef.resetFields();
        }
      },
    },
    created() {
      this.getProductList();
      this.getDeviceList();
      this.getInfo();
    },
    methods: {
        upload(res){
            // console.log(res);
            this.editDeviceForm.savepath = res.savepath
        },
      addProductSucc(form) {
        this.getInfo();
        this.getProductList();
      },
      getProductList() {
        this.productLoading = true;
        this.http.$post('admin2/product.api/product_list', {
          curr: this.curr,
          limits: this.limits,
          customer_id: this.$route.params.id,
        }).then(res => {
          this.productLoading = false;
          this.productList = res.list;
          this.total = res.total;
        }).catch(e => {
          this.$err(e);
          this.productLoading = false;
        });
      },
      getSelects() {
        let item = this.cusInfoLabel.find(e => e.prop === 'bus_id');
        let list = this.cusInfoLabel.find(e => e.prop === 'type_id');
        if (item && item.options && !item.options.length) {
          this.http.$post('admin/salesman.Api/customer_salesman_lists', {
            status: 1,
            company_id: this.userInfo.company_id,
          }).then(res => {
            item.options = res;
          }).catch(console.log);
        }
        if (list && list.options && !list.options.length) {
          this.http.$post('admin2/customer_type.Api/customer_type_all_list').then(res => {
            list.options = res;
          }).catch(console.log);
        }
      },
      editDevice(row) {
        if (row) {
          row = {...row};
          row.model_data_list = [...row.model_data_list];
          row.file_path = row.model_icon;
        } else {
          row = {
            model_data_list: [],
            file_path: '',
          };
        }
        let label = this.editDeviceLabel.find(e => e.type === 'upload');
        label.res = row;
        this.editDeviceForm = row;
        this.editDeviceInner = true;
      },
      delDevice(row) {
        this.$confirm('确定删除该设备？', '提示').then(res => {
          this.http.$post('admin/device.Api/device_del', {
            model_id: row.model_id,
            status: 2,
          }).then(r => {
            this.$message.success('删除成功');
            this.getDeviceList();
          }).catch(this.$err);
        }).catch(console.log)
      },
      editDeviceSure() {
        let url = 'admin/device.Api/device_add';
        let params = {...this.editDeviceForm};
        if (params.model_id) {
          url = 'admin/device.Api/device_edit';
        }
        params.customer_id = params.customer_id || this.$route.params.id;
        params.list = params.model_data_list;
        params.model_icon = params.savepath;
        console.log(params);
        this.http.$post(url, params).then(res => {
          this.$message.success(this.editDeviceForm.model_id ? '修改成功' : '添加成功');
          this.getDeviceList();
          this.editDeviceInner = false;
        }).catch(this.$err);
      },
      edit() {
        let passInfo = this.$refs.infoRef.validate();
        let passLogin = this.$refs.loginRef.validate();
        if (!passInfo || !passLogin) return;
        this.http.$post('admin2/customer.api/save_customer', {
          ...this.cusInfo,
          ...this.login,
        }).then(res => {
          this.$message.success('修改成功');
          this.getInfo();
          setTimeout(() => {
            this.showEdit = false;
          }, 1000);
        }).catch(this.$err);
      },
      currChange({curr, size}) {
        this.curr = curr;
        this.limits = size;
        this.getProductList();
      },
      getDeviceList() {
        this.http.$post('admin/device.Api/device', {
          customer_id: this.$route.params.id,
          limits: 1000,
        }).then(res => {
          this.deviceList = res.list;
        }).catch(console.log);
      },
      getInfo() {
        this.http.$post('admin/customer.api/get_customer_info', {
          id: this.$route.params.id,
        }).then(res => {
          this.info = res;
        }).catch(console.log);
      },
      toAct(row) {
        this.$router.push({
          name: 'CustomerRegisterDevice',
          query: {
            id: row.id,
            sum: row.sum,
            act_sum: row.act_sum,
          },
        })
      },
      btnCallback({row, column, index}) {
        if (index) {
          // 订单详情
          this.$router.push({
            name: 'CustomerOrderDetails',
            query: {
              id: this.$route.params.id,
              pid: row.id,
              name: this.info.name,
              pname: row.name,
            },
          })
        } else {
          // 产品详情
          this.$router.push({
            name: 'produceDetail',
            query: {
              id: row.id,
            },
          })
        }
      },
      infoCallback(prop) {
        switch (prop) {
          case 'userSum':
            this.$router.push({
              name: 'CustomerRegisterUser',
              query: {
                id: this.$route.params.id,
                name: this.info.name
              }
            });
            break;
          case 'contract_num':
            this.$router.push({
              name: 'CustomerContract',
              query: {
                id: this.$route.params.id,
              }
            });
            break;
        }
      },
    },
  }
</script>

<style scoped lang="less">
  .bg {
    background-color: #fff;
    border-radius: 4px;
  }

  .df-title {
    padding-left: 15px;
    color: #333;
    font-weight: bold;
    border-left: 5px solid #409EFF;
    line-height: 30px;
  }

  .cus-detail {
    line-height: 1.5;
    font-size: 18px;
    color: #666;
    .name {
      font-size: 22px;
      font-weight: bold;
      color: #333;
    }
    .type {
      color: #999;
      font-size: 16px;
    }
  }

  .info {
    padding: 20px 0;
    background-color: #e6f7ff;
    border: 1px solid #91d5ff;
    border-radius: 5px;
    font-size: 16px;
    color: #666;
    .prop {
      color: #333;
    }
    .info-label {
      &:not(:last-child) {
        border-right: 2px solid #91d5ff;
      }
    }
    .can-click {
      color: #91d5ff;
      cursor: pointer;
    }
  }

  .def-title {
    .span {
      line-height: 40px;
      padding-left: 10px;
      font-weight: bold;
      border-left: 4px solid #91d5ff;
    }
  }

  .act-count {
    color: #91d5ff;
  }

  .device-item {
    width: 45%;
    align-items: center;
    border: 1px #ddd solid;
    font-size: 14px;
    color: #666;
    .device-img {
      width: 134px;
      height: 100px;
      border-radius: 5px;
    }
    .dev-name {
      color: #333;
      font-size: 20px;
    }
  }

  .device-dialog {
    .img {
      max-height: 100%;
    }
    .title {
      line-height: 2;
      background-color: rgba(0, 0, 0, .6);
      color: #fff;
    }
    .item {
      width: 150px;
      height: 150px;
      line-height: 150px;
      border: 1px #ddd solid;
      &:hover {
        .btns {
          transform: translateY(0);
        }
      }
    }
    .add-item {
      border-radius: 5px;
      & ~ .item {
        border: 0;
      }
    }
    .btns {
      right: 5px;
      line-height: 1;
      transform: translateY(-100%);
    }
    .el-button {
      padding: 0;
      line-height: 1.5;
      font-size: 16px;
      font-weight: bold;
    }
  }

  .remark {
    align-items: center;
  }
</style>